package cn.sycoder.utils;

import cn.sycoder.auth.AuthInfo;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.common.base.Preconditions;
import io.jsonwebtoken.impl.crypto.JwtSigner;

import java.io.UnsupportedEncodingException;
import java.sql.Statement;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil2 {

    public static String USER_ID = "userId";
    public static String USER_NAME = "userName";
    public static String USER_ROLES = "userRoles";

    /**
     * 使用jwt 生成token
     *
     * @param authInfo
     * @param expireDate
     * @param secret
     * @return
     */
    public static String getToken(AuthInfo authInfo, Date expireDate, String secret) {
//        if (obj != null){
//
//        }
        Preconditions.checkArgument(authInfo != null, "加密内容不能为 null");
        Preconditions.checkArgument(expireDate != null, "过期时间异常！");
        Preconditions.checkArgument(secret != null, "密码不能为 null");
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        String token = null;//签名
        try {
            token = JWT.create()
                    .withHeader(map)//头
//                    .withSubject("测试")
                    .withClaim(USER_ID,authInfo.getUserId())
                    .withClaim(USER_NAME,authInfo.getUserName())
                    .withClaim(USER_ROLES,authInfo.getRoles())
                    .withIssuedAt(new Date())//签名时间
                    .withExpiresAt(expireDate)//过期时间
                    .sign(Algorithm.HMAC256(secret));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return token;
    }


    /**
     * 验证 Token，返回authInfo对象
     * @param token
     * @return
     * @throws Exception
     */
    public static AuthInfo verifyToken(String token,String secret){
        JWTVerifier verifier = null;
        try {
            verifier = JWT.require(Algorithm.HMAC256(secret)).build();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
        }catch (Exception e){
            throw new RuntimeException("凭证已过期，请重新登录");
        }
        AuthInfo authInfo = new AuthInfo();
        authInfo.setUserId(jwt.getClaim(USER_ID).asLong());
        authInfo.setUserName(jwt.getClaim(USER_NAME).asString());
        authInfo.setRoles(jwt.getClaim(USER_ROLES).asString());
        return authInfo;
    }

    // 测试
    public static void main(String[] args) {

        AuthInfo authInfo = new AuthInfo();
        authInfo.setUserName("zhangsan");
        authInfo.setUserId(1L);
        authInfo.setRoles("admin");

        Date date = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
        String token = getToken(authInfo, date, "123456");
        AuthInfo info = verifyToken(token, "123456");
        System.out.println(info);
    }
}
